﻿using BLL;
using DAL;
using DevComponents.DotNetBar.Controls;
using Mapster;
using Model;
using Newtonsoft.Json;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;
using 后整理管理系统.基本资料;
using 后整理管理系统.自定义类;
using 纺织贸易管理系统.其他窗体;
using 纺织贸易管理系统.设置窗体;
using 纺织贸易管理系统.选择窗体;

namespace 纺织贸易管理系统.新增窗体
{
    public partial class 辅料销售单 : Form
    {
        public FormUseful useful { get; set; } = FormUseful.新增;
        public List<danjumingxitable> danjumingxitables = new List<danjumingxitable>();
        public DanjuTable danju = new DanjuTable();
        private List<JuanHaoTable> juanList = new List<JuanHaoTable>();
        private int rowindex;
        private string State = string.Empty;
        public List<AccessoriesInfo> AccessoriesInfos = new List<AccessoriesInfo>();
        public List<ImportAndExportOfRawMaterials> Raws = new List<ImportAndExportOfRawMaterials>();
        public List<ManualCode> manualCodes = new List<ManualCode>();
        public  List<StockTable> stockTables = new List<StockTable>();
        public List<JuanHaoTable> InitJuans = new List<JuanHaoTable>();//可以传入的卷
        private Boolean SaveState = false;
        public 辅料销售单()
        {
            InitializeComponent();
            CreateGrid.Create(this.Name, gridView1);
            CreateGrid.Create(this.Name, gridView2);
            CreateGrid.Create(this.Name, gridView3);
            CreateGrid.Create(this.Name, gridView4);
            //LUEKuwei.NullText = string.Empty;
            //LUEKuwei.DisplayMember = "JiaziID";
            //LUEKuwei.ValueMember = "JiaziID";
            //LUEKuwei.DataSource=JiaziTableService .GetJiaziTablelst(x=>x.State =="自己公司");
            try
            {
                gridView1.Columns["Bianhao"].ColumnEdit = ButtonEdit1;
                gridView1.Columns["pingming"].ColumnEdit = ButtonEdit1;
                gridView1.Columns["OrderNum"].ColumnEdit = ButtonEdit1;
                gridView3.Columns["Bianhao"].ColumnEdit = repositoryItemButtonEdit1;
                gridView3.Columns["pingming"].ColumnEdit = repositoryItemButtonEdit1;
                gridView3.Columns["OrderNum"].ColumnEdit = repositoryItemButtonEdit1;
                gridView4.Columns["ProductName"].ColumnEdit = repositoryItemButtonEdit5;
                gridView1.Columns["danwei"].ColumnEdit = cmddanwei;
                gridView1.Columns["hanshuiheji"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                gridView1.Columns["hanshuiheji"].SummaryItem.FieldName = "hanshuiheji";
                gridView1.Columns["hanshuiheji"].SummaryItem.DisplayFormat = "{0:0.##}";
                gridView1.Columns["chengpingmishu"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                gridView1.Columns["chengpingmishu"].SummaryItem.FieldName = "chengpingmishu";
                gridView1.Columns["chengpingmishu"].SummaryItem.DisplayFormat = "{0:0.##}";
                gridView1.Columns["chengpingjuanshu"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                gridView1.Columns["chengpingjuanshu"].SummaryItem.FieldName = "chengpingjuanshu";
                gridView1.Columns["chengpingjuanshu"].SummaryItem.DisplayFormat = "{0:0.##}";
                gridView1.Columns["IsHanshui"].ColumnEdit = cmbHanshui;
                gridView2.Columns["rq"].DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";//设置时间显示格式
                //gridView1.Columns["Kuwei"].ColumnEdit = LUEKuwei;
                cmbMadanYangshi.Text = SettingService.GetSetting(new Setting() { formname = this.Name, settingname = "码单样式", settingValue = "" }).settingValue;
            }
            catch
            {
                配置列ToolStripMenuItem_Click(null, null);
            }
        }

        private void 配置列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView1) { formname = this.Name, Obj = new danjumingxitable() };
            fm.ShowDialog();
        }

        private void txtkehu_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var fm = new 客户选择() { linkman = new LXR() { MC = "", ZJC = "" } };
            fm.ShowDialog();
            danju.ksbh = fm.linkman.BH;
            danju.ksmc = fm.linkman.MC;
            txtkehu.Text = danju.ksmc;
        }

        private void txtwuliu_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var fm = new 物流选择();
            fm.ShowDialog();
            danju.wuliuBianhao = fm.linkman.Bianhao;
            txtwuliu.Text = fm.linkman.name;
            var wuliu = fm.linkman;
            txtchepai.Text = wuliu.CarNum;
            txtlianxiren.Text = wuliu.name;
            txtQicheleixing.Text = wuliu.CarLeixing;
        }

        private void txtckmc_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var fm = new 仓库选择();
            fm.ShowDialog();
            txtckmc.Text = fm.stock.mingcheng;
            加载卷();
        }
        /// <summary>
        /// 选择布料
        /// </summary>
        private void SelectFabric()
        {
            if (txtckmc.Text == "")
            {
                MessageBox.Show("请先选择仓库名称", "错误", MessageBoxButtons.OK);
                return;
            }
            //if (string.IsNullOrWhiteSpace(txtkehu.Text))
            //{
            //    MessageBox.Show("请先选择客户名称", "错误", MessageBoxButtons.OK);
            //    return;
            //}
            var fm = new 库存选择() { StockName = txtckmc.Text };
            fm.ShowDialog();
            StockToDanjumingxi(fm.pingzhong );//根据库存转成单据明细
            加载卷();
            fm.Dispose();
        }
        /// <summary>
        /// 根据库存转换成单据明细
        /// </summary>
        /// <param name="stocks"></param>
        private void StockToDanjumingxi(List<StockTable > stocks )
        {
           SelectHelper.StockConverToDanjumingxi(gridView1,stocks ,danjumingxitables,txtdanhao.Text ,dateEdit1.DateTime,DanjuLeiXing.销售出库单 );
            自动填写价格();
            gridControl1.DataSource = danjumingxitables;
            gridControl1.RefreshDataSource();
            gridView1.CloseEditor();
            检查其他费用();
            txtbeizhu.Text = danjumingxitables[0].houzhengli;
        }
        private void ButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            SelectFabric();
        }
        private void 自动填写价格()
        {
            if (AccessBLL.CheckAccess("销售价格填写"))
            {
                foreach (var houzhengli in danjumingxitables.Where (x=>!string.IsNullOrEmpty( x.pingming) ).Select (x=>x.houzhengli ).Distinct ().ToList ())
                {
                    if (!string.IsNullOrEmpty(houzhengli))
                    {
                        var dt = Connect.dbcontext.Queryable<DanjuTable>().LeftJoin<danjumingxitable>((x, y) => x.dh == y.danhao).Where((x, y) => x.ksmc == txtkehu.Text && y.houzhengli == houzhengli).Select<danjumingxitable>().OrderByDescending(x => x.ID).ToList();
                        if (dt.Count > 0)
                        {
                            foreach (var mingxi in danjumingxitables.Where(x => !string.IsNullOrEmpty(x.pingming)).ToList())
                            {
                                mingxi.hanshuidanjia = dt[0].hanshuidanjia;
                                mingxi.hanshuiheji = mingxi.hanshuidanjia * mingxi.toupimishu;
                            }
                        }
                    }
                }
            }
        }
        private void 检查其他费用()
        {
            foreach (var d in danjumingxitables.Where(x => x.OrderNum != null).Select(x => x.OrderNum).Distinct().ToList())
            {
                if (订单BLL.CheckOtherCost(d) == true)
                {
                    if (销售发货单BLL.CheckDanjuMingxiContainOtherCost(d) == false)
                    {
                        this.ShowAskDialog( $"改订单号{d }存在其他费用！而且对账单还没体现过！");
                    }
                }
            }
        }
        
        private void 加载卷()
        {
            new StockHelper() { danjumingxitables=danjumingxitables,txtkehu=txtkehu}.加载卷(juanList, gridControl2,txtckmc.Text );
          
        }
        private void ButtonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var fm = new 订单号选择();
            fm.ShowDialog();
            danjumingxitables[gridView1.FocusedRowHandle].OrderNum = fm.Order.OrderNum;
            danjumingxitables[gridView1.FocusedRowHandle].CustomName = fm.Order.CustomerName;
            danjumingxitables[gridView1.FocusedRowHandle].ContractNum = fm.Order.ContractNum;
            gridControl1.RefreshDataSource();
            gridView1.CloseEditor();
        }
     #region 添加删除行
        private void 删除行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView1.DeleteRow(gridView1.FocusedRowHandle);
            加载卷();
            ComputeTotalMoney();
        }
   
        private void 添加行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            danjumingxitables.Add(new danjumingxitable() { danhao = txtdanhao.Text, rq = Convert.ToDateTime(dateEdit1.Text) });
        }

        private void 复制行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rowindex = gridView1.FocusedRowHandle;
        }

        private void 粘贴行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CopyRow.Copy<danjumingxitable>(danjumingxitables, rowindex, gridView1, gridView1.FocusedRowHandle, this);
        }
        #endregion
        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                juanList.Where(x => x.GangHao == danjumingxitables[gridView1.FocusedRowHandle].ganghao).ToList().ForEach(x => x.Houzhengli = danjumingxitables[gridView1.FocusedRowHandle].houzhengli);
                juanList.Where(x => x.GangHao == danjumingxitables[gridView1.FocusedRowHandle].ganghao).ToList().ForEach(x => x.kuanhao = danjumingxitables[gridView1.FocusedRowHandle].kuanhao);
                juanList.Where(x => x.GangHao == danjumingxitables[gridView1.FocusedRowHandle].ganghao).ToList().ForEach(x => x.Huahao = danjumingxitables[gridView1.FocusedRowHandle].Huahao);
                juanList.Where(x => x.GangHao == danjumingxitables[gridView1.FocusedRowHandle].ganghao).ToList().ForEach(x => x.OrderNum = danjumingxitables[gridView1.FocusedRowHandle].OrderNum);
              if(gridView1.FocusedColumn.FieldName == "danwei")
                {
                    if(juanList.Count >0)
                    {
                        if (juanList[0].Danwei =="码"&& danjumingxitables[gridView1.FocusedRowHandle].danwei=="米" )
                        {
                            danjumingxitables[gridView1.FocusedRowHandle].toupimishu = juanList[0].MaShu != 0 ? danjumingxitables[gridView1.FocusedRowHandle].chengpingmishu * (juanList[0].MaShu / 100)*(decimal )0.9144 : danjumingxitables[gridView1.FocusedRowHandle].chengpingmishu*(decimal )0.9144;
                        }
                        if (juanList[0].Danwei == "码" && danjumingxitables[gridView1.FocusedRowHandle].danwei == "码")
                        {
                            danjumingxitables[gridView1.FocusedRowHandle].toupimishu = juanList[0].MaShu != 0 ? danjumingxitables[gridView1.FocusedRowHandle].chengpingmishu * (juanList[0].MaShu / 100) : danjumingxitables[gridView1.FocusedRowHandle].chengpingmishu;
                        }
                    }
                }
                danjumingxitables[gridView1.FocusedRowHandle].toupimishu = danjumingxitables[gridView1.FocusedRowHandle].chengpingmishu;
                danjumingxitables[gridView1.FocusedRowHandle].hanshuiheji = danjumingxitables[gridView1.FocusedRowHandle].hanshuidanjia * danjumingxitables[gridView1.FocusedRowHandle].toupimishu;
                //}
                //else
                //{
                //    danjumingxitables[gridView1.FocusedRowHandle].hanshuiheji = danjumingxitables[gridView1.FocusedRowHandle].hanshuidanjia * danjumingxitables[gridView1.FocusedRowHandle].chengpingmishu ;
                //}
                gridControl2.RefreshDataSource();
                gridControl1.RefreshDataSource();
                ComputeTotalMoney();
            }
            catch
            {
                MessageBox.Show("请输入数字。计算错误");
            }
        }
        /// <summary>
        /// 计算合计金额
        /// </summary>
        private void ComputeTotalMoney()
        {
            //danjumingxitables.Sum(x => x.hanshuiheji) + danjumingxitables.Sum(x => x.weishuiheji)
            txtTotalMoney.Text = ((double)danjumingxitables.Sum(x => x.hanshuiheji)+(double ) danjumingxitables.Sum(x => x.weishuiheji) + StevedoringChargesFreeNuminput.Value + PackagingFeeNuminput.Value + FlowerRollerFeeNuminput.Value + OtherNuminput.Value).ToString("N2");
        }
        //给单据信息赋值
        private void InitDanju()
        {
            ComputeTotalMoney();
            danju.bz = txtbeizhu.Text;
            danju.CarLeixing = txtQicheleixing.Text;
            danju.CarNum = txtchepai.Text;
            danju.ckmc = txtckmc.Text;
            danju.StockName = cmbcunfang.Text;
            danju.dh = txtdanhao.Text;
            danju.djlx = DanjuLeiXing.辅料销售单;
            danju.rq = dateEdit1.DateTime;
            danju.shouhuodizhi = txtShouhuodizhi.Text;
            danju.lianxiren = txtlianxiren.Text;
            danju.Qiankuan = cmbqiankuan.Text;
            danju.Hanshui = IsHanshuiModel.含税;
            danju.je = txtTotalMoney.Text .ObjToDecimal ();
            danju.totaljuanshu = danjumingxitables.Sum(x => x.chengpingjuanshu);
            danju.TotalMishu = danjumingxitables.Sum(x => x.chengpingmishu);
            danju.wuliugongsi = txtwuliu.Text;
            danju.yunfei = (decimal)txtyunfei.Value;
            danju.lianxidianhua = txtlianxidianhua.Text;
            danju.own =CurrentUser.user.YHBH;
            danju.Bizhong = cmbbizhong.Text;
            danju.remarker = txtbeizhu.Text;
            danju.fromDanhao = txtFromDanhao.Text;
            danju.yaoqiu = checkBox1.Checked ? "复合" : string.Empty;
            danju.toupimishu = danjumingxitables.Sum(x => x.toupimishu);
            danju.toupijuanshu = danju.totaljuanshu;
            danju.OtherFees = (decimal)OtherNuminput.Value;
            danju.FlowerRollerFee = (decimal)FlowerRollerFeeNuminput.Value;
            danju.PackagingFee = (decimal)PackagingFeeNuminput.Value;
            danju.StevedoringChargesFree = (decimal)StevedoringChargesFreeNuminput.Value;
            //danju.Fahuodizhi = txtjiagongchang.Text;
        }
        private List<JuanHaoTable> CreatJuanhao()
        {
            var juan = new List<JuanHaoTable>();
            foreach (var j in gridView2.GetSelectedRows())
            {
                var selectjuan = juanList.FirstOrDefault(x => x.ID == (int)gridView2.GetRowCellValue(j, "ID"));
                selectjuan.Houzhengli = danjumingxitables[0].houzhengli;
                juan.Add(selectjuan);
            }
            return juan;
        }
        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (StockHelper.CheckMashu(CreatJuanhao()))
            {
                Tools.ShowMessageBox.ShowErrorBox("单据存在两种不同的挂码！不能打印单据！");
                return;
            }
            if (StockHelper.CheckDanWei(CreatJuanhao()))
            {
                Tools.ShowMessageBox.ShowErrorBox("单据存在两种不同的卷单位！不能打印单据！");
                return;
            }
            CloseEdit();
            if(Tools.ShowMessageBox.ShowAskBox("已打勾的保存后将会清掉库存！请确认已发完的勾选是否正确")==DialogResult.No )
            {
                return;
            }
            if (string.IsNullOrEmpty (txtkehu.Text))
            {
                Tools.ShowMessageBox.ShowErrorBox("客户名称必须填写！保存失败");
                return;
            }
            if (dateEdit1.DateTime.ToShortDateString() !=DateTime.Today.ToShortDateString ())
            {
              if(  MessageBox.Show("单据日期与系统日期不匹配？\r\n是否继续保存", this.Name, MessageBoxButtons.YesNo , MessageBoxIcon.Information)!=DialogResult.Yes )
                {
                    return;
                }
            }
            if (gridView2.SelectedRowsCount == 0)
            {
                if (juanList.Count > 0)
                {
                    MessageBox.Show("没有任何卷被选中！保存失败", this.Name, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            
            if (danjumingxitables.Where(x=>!string.IsNullOrWhiteSpace(x.pingming )&&x.chengpingmishu==0&&x.chengpingjuanshu==0).Count()>0)
            {
                ShowMessageBox.ShowErrorBox("单据存在发货数量是0  发货卷数也是0的信息！\r\n保存失败");
                return;
            }
            if (danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).Count() == 0)
            {
                ShowMessageBox.ShowErrorBox("检测不到任何布料信息！\r\n保存失败");
                return;
            }
            if (QueryTime.IsMustNeedTel)
            {
                if (string.IsNullOrEmpty(LXRService.GetOneLXR (x=>x.MC ==txtkehu.Text ).DH))
                {
                    Tools.ShowMessageBox.ShowErrorBox("当前策略为客户必须要有联系电话！检测不到该客户的联系电话！");
                    return;
                }
            }
            InitDanju();
            try
            {
                Connect.dbcontext.BeginTran();
                if (useful == FormUseful.新增)
                {
                    if (财务BLL.查询额度(danju.ksbh, danjumingxitables.Sum(x => x.hanshuiheji)) == false)
                    {
                        if (Tools.ShowMessageBox.ShowAskBox("该客户欠款额度已经不够了！是否继续保存") != DialogResult.Yes)
                        {
                            return;
                        }
                    }
                    if (SettingService.GetSetting(x => x.settingname == "检查账期").settingValue == "检查")
                    {
                        if (财务BLL.检查是否有超期(danju.ksbh))
                        {
                            MessageBox.Show("该客户存在超期单据！保存失败", this.Name, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                    }
                    danju.IsPrinter = State;
                    销售发货单BLL.保存单据(danju, danjumingxitables, CreatJuanhao(), AccessoriesInfos.Where(x=>!string.IsNullOrEmpty( x.pingming) ).ToList (), Raws.Where(x=>!string.IsNullOrEmpty(x.ProductName)).ToList ());
                }
                else
                {
                    danju.IsPrinter = string.IsNullOrEmpty(State) ? string.Empty : State;
                    销售发货单BLL.修改单据(danju, danjumingxitables, CreatJuanhao(), AccessoriesInfos.Where(x => !string.IsNullOrEmpty(x.pingming)).ToList(), Raws.Where(x => !string.IsNullOrEmpty(x.ProductName)).ToList());
                }
                if (!string.IsNullOrWhiteSpace(SysInfo.GetInfo.own))
                {
                    if (SysInfo.GetInfo.own == "审核制")
                    {
                        if ((int)(MessageBox.Show("是否直接审核过账？", this.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Information)) == 6)
                        {
                            销售发货单BLL.单据审核(danju.dh);
                            //检测状态.检测(danjumingxitables);
                        }
                    }
                    else
                    {
                        //检测状态.检测(danjumingxitables);
                    }
                }
                ///保存手工码单
                
                Connect.dbcontext.Deleteable<ManualCode>().Where(x => x.DocNum == txtdanhao.Text).ExecuteCommand();
                Connect.dbcontext.Insertable<ManualCode>(manualCodes.Where(x => x.Col1 > 0).ToList()).ExecuteCommand();
                Connect.dbcontext.CommitTran();
                AlterDlg.Show("保存成功");
                SaveState = !SaveState;
                if (QueryTime.PrintRule == PrintRuleStyle.SaveFirst)
                {
                    useful = FormUseful.修改;
                }
                else
                {
                    useful = FormUseful.新增;
                }
                SaveStateChange();
               
                //清空所有控件

            }
            catch(Exception ex)
            {
                Connect.dbcontext.RollbackTran();
                ShowMessageBox.ShowErrorBox("保存单据的时候发生了错误:" + ex.Message);

            }
        }
        /// <summary>
        /// 初始化新单据
        /// </summary>
        private void Init()
        {
            foreach (Control c in this.groupControl1.Controls)
            {
                if (c is DevComponents.DotNetBar.Controls.TextBoxX)
                {
                    c.Text = "";
                }
                if (c is DevExpress.XtraEditors.ButtonEdit)
                {
                    c.Text = "";
                }
            }
            txtjiagongchang.Text = "";
           
            dateEdit1.DateTime = DateTime.Now;
            txtdanhao.Text = BianhaoBLL.CreatDanhao(FirstLetter.辅料销售单, dateEdit1.DateTime, DanjuLeiXing.辅料销售单);
            //danjumingxitables =Connect.dbcontext.Queryable<danjumingxitable>().Where (x => x.danhao == txtdanhao.Text).ToList ();
            danjumingxitables.Clear();
            AccessoriesInfos.Clear();
            Raws.Clear();
            manualCodes.Clear();
            checkBox1.Checked = false;
            var length = danjumingxitables.Count;
            for (int i = 0; i < 30 - length; i++)
            {
                danjumingxitables.Add(new danjumingxitable() { danhao = txtdanhao.Text, rq = dateEdit1.DateTime });
                AccessoriesInfos.Add(new AccessoriesInfo() { danhao = txtdanhao.Text, rq = dateEdit1.DateTime });
                Raws.Add(new ImportAndExportOfRawMaterials() { DocNum = txtdanhao.Text });
                manualCodes.Add(new ManualCode() { DocNum = txtdanhao.Text });
            }
            gridControl1.DataSource = danjumingxitables;
            gridControl1.RefreshDataSource();
            //gridControl2.DataSource = null;
            gridControl3.DataSource = AccessoriesInfos;
            gridControl4.DataSource = Raws;
            gridControl5.DataSource = manualCodes;
            juanList.Clear();
            gridControl2.DataSource = juanList;
            gridControl3.RefreshDataSource();
            gridControl4.RefreshDataSource();
            gridControl5.RefreshDataSource();
            txtckmc.Text = QueryTime.DefaultStock;
            StevedoringChargesFreeNuminput.Value = 0;
            PackagingFeeNuminput.Value = 0;
            FlowerRollerFeeNuminput.Value = 0;
            OtherNuminput.Value = 0;
            txtTotalMoney.Text = "0.00";
            useful = FormUseful.新增;         
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView2) { formname = this.Name, Obj = new JuanHaoTable() };
            fm.ShowDialog();
        }
        /// <summary>
        /// 勾选细码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView2_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {

            new StockHelper() { DetailgridControl = gridControl1, MinxiGridview = gridView1, danjumingxitables = danjumingxitables,juanList=juanList }.SelectionChange(gridView2);
        }
        /// <summary>
        /// 未保存不能新增和打印
        /// </summary>
        private void SaveStateChange()
        {
            if (QueryTime.PrintRule == PrintRuleStyle.SaveFirst)
            {
                if (useful == FormUseful.新增)
                {
                    if (ShowMessageBox.ShowAskBox("是否继续新增操作？") == DialogResult.Yes)
                    {
                        //清空所有控件
                        Init();
                    }
                    else
                    {
                        MainForm.mainform.CloseTab();
                    }
                }
                if (SaveState)
                {
                    新增ToolStripMenuItem.Enabled = true;
                    修改ToolStripMenuItem.Enabled = true;
                    打印码单ToolStripMenuItem.Enabled = true;
                    打印单据ToolStripMenuItem.Enabled = true;
                    保存ToolStripMenuItem.Enabled = false;
                }
                else
                {
                    新增ToolStripMenuItem.Enabled = false;
                    修改ToolStripMenuItem.Enabled = false;
                    打印码单ToolStripMenuItem.Enabled = false;
                    打印单据ToolStripMenuItem.Enabled = false;
                    保存ToolStripMenuItem.Enabled = true;
                }
            }
            else
            {
                新增ToolStripMenuItem.Visible = false;
                修改ToolStripMenuItem.Visible = false;
                if (useful == FormUseful.新增)
                {
                    if (ShowMessageBox.ShowAskBox("是否继续新增操作？") == DialogResult.Yes)
                    {
                        //清空所有控件
                        Init();
                    }
                    else
                    {
                        MainForm.mainform.CloseTab();
                    }
                }
            }
        }
        private void 销售发货单_Load(object sender, EventArgs e)
        {
            if (useful == FormUseful.新增)
            {
                //Init();
                SaveStateChange();
               this.ShowWaitForm("正在创建单据，请稍后....");
                if (InitJuans.Count > 0)
                {
                    CreateDanjuWithJuanhaotable();//根据细码生成出库单
                }
                else
                {
                    //如果传入的卷不为空的时候就是按卷生成发货单
                    if (stockTables.Count > 0)
                    {
                        CreateDanjuWithDanjumingxi();//从入库单信息直接生成出库单
                    }
                }
              
               this.HideWaitForm();
            }
            else
            {
                Edit();
                SaveStateChange();
                if (useful == FormUseful.查看)
                {
                    保存ToolStripMenuItem.Enabled = false;
                }
                ///初始化表格信息
            InitGridControl();
            }
            ComputeTotalMoney();

        }
        /// <summary>
        /// 根据细码生成单据
        /// </summary>
        private void CreateDanjuWithJuanhaotable()
        {
            //初始化单据信息
            if (stockTables.Count > 0)
            {
                txtckmc.Text = stockTables[0].CKMC;
                txtkehu.Text = stockTables[0].CustomName;
                var lxr = LXRService.GetOneLXR(x => x.MC == txtkehu.Text);
                if (lxr != null)
                {
                    danju.ksbh = lxr.BH;
                    danju.ksmc = lxr.MC;
                }
            }
            StockToDanjumingxi(stockTables);//生成单据明细
            juanList =JsonConvert.DeserializeObject<List<JuanHaoTable >>( JsonConvert.SerializeObject( InitJuans));
            InitJuans.Clear();
            gridControl2.DataSource = juanList;
            //把所有的细码都打上勾
            SetAllSelect();
        }
        /// <summary>
        /// 根据单据明细生成单据
        /// </summary>
        private void CreateDanjuWithDanjumingxi()
        {
            //初始化单据信息
            if (stockTables.Count > 0)
            {
                txtckmc.Text = stockTables[0].CKMC;
                txtkehu.Text = stockTables[0].CustomName;
                var lxr = LXRService.GetOneLXR(x => x.MC == txtkehu.Text);
                if (lxr != null)
                {
                    danju.ksbh = lxr.BH;
                    danju.ksmc = lxr.MC;
                }
            }
            StockToDanjumingxi(stockTables);//生成单据明细
            加载卷();
            //把所有的细码都打上勾
            SetAllSelect();
        }
        /// <summary>
        /// 把所有的细码全部选中
        /// </summary>
        private void SetAllSelect()
        {
            for (int rowindex = 0; rowindex < gridView2.RowCount; rowindex++)
            {
                    gridView2.SelectRow(rowindex);
            }
        }
        /// <summary>
        /// 修改单据或者查看的时候初始化表格信息
        /// </summary>
        private void InitGridControl()
        {
            juanList = Connect.dbcontext.Queryable<JuanHaoTable>().Where(x => x.Danhao == txtdanhao.Text).OrderBy(x => x.GangHao).ToList(); ;
            gridControl2.DataSource = juanList;
            for (int rowindex = 0; rowindex < juanList.Count; rowindex++)
            {
                var juan = juanList[rowindex];
                if (juan.Danhao == txtdanhao.Text)
                {
                    gridView2.SelectRow(rowindex);
                }
            }
            danjumingxitables = Connect.dbcontext.Queryable<danjumingxitable>().Where(x => x.danhao == danju.dh).ToList();
            var length = danjumingxitables.Count;
            for (int i = 0; i < 30 - length; i++)
            {
                danjumingxitables.Add(new danjumingxitable() { danhao = txtdanhao.Text, rq = dateEdit1.DateTime });
            }
            gridControl1.DataSource = danjumingxitables;
            //加载底布信息
            AccessoriesInfos = Connect.dbcontext.Queryable<AccessoriesInfo>().Where(x => x.danhao == danju.dh).ToList();
            length = AccessoriesInfos.Count;
            for (int i = 0; i < 30 - length; i++)
            {
                AccessoriesInfos.Add(new AccessoriesInfo() { danhao = txtdanhao.Text, rq = dateEdit1.DateTime });
            }
            gridControl3.DataSource = AccessoriesInfos;
            //加载原料信息
            Raws = Connect.dbcontext.Queryable<ImportAndExportOfRawMaterials>().Where(x => x.DocNum == danju.dh).ToList();
            length = Raws.Count;
            for (int i = 0; i < 30 - length; i++)
            {
                Raws.Add(new ImportAndExportOfRawMaterials() { DocNum = txtdanhao.Text });
            }
            gridControl4.DataSource = Raws;
            //加载原料信息
            manualCodes = Connect.dbcontext.Queryable<ManualCode>().Where(x => x.DocNum == danju.dh).ToList();
            length = Raws.Count;
            for (int i = 0; i < 50 - length; i++)
            {
                manualCodes.Add(new ManualCode() { DocNum = txtdanhao.Text });
            }
            gridControl5.DataSource = manualCodes;
        }
        private void Edit()
        {
            txtdanhao.Text = danju.dh;
            txtbeizhu.Text = danju.bz;
            txtchepai.Text = danju.CarNum;
            txtckmc.Text = danju.ckmc;
            cmbcunfang.Text = danju.StockName;
            txtkehu.Text = danju.ksmc;
            txtlianxidianhua.Text = danju.lianxidianhua;
            txtlianxiren.Text = danju.lianxiren;
            txtQicheleixing.Text = danju.CarLeixing;
            txtwuliu.Text = danju.wuliugongsi;
            txtyunfei.Text = danju.yunfei.ToString();
            cmbqiankuan.Text = danju.Qiankuan;
            checkBox1.Checked = danju.yaoqiu == "复合";
            //danju.Fahuodizhi = txtjiagongchang.Text;
            //comhanshui.Text = danju.Hanshui;
            dateEdit1.DateTime = danju.rq;
            txtFromDanhao.Text = danju.fromDanhao;
            StevedoringChargesFreeNuminput.Value =(double ) danju.StevedoringChargesFree.ObjToDecimal ();
            PackagingFeeNuminput.Value = (double)danju.PackagingFee.ObjToDecimal();
            FlowerRollerFeeNuminput.Value = (double)danju.FlowerRollerFee.ObjToDecimal();
            OtherNuminput.Value = (double)danju.OtherFees.ObjToDecimal();
        }

        private void PrintMadan(PrintModel  printsytle)
        {
            if (StockHelper.CheckMashu(CreatJuanhao()))
            {
                Tools.ShowMessageBox.ShowErrorBox("单据存在两种不同的挂码！不能打印单据！");
                return;
            }
            if (StockHelper.CheckDanWei(CreatJuanhao()))
            {
                Tools.ShowMessageBox.ShowErrorBox("单据存在两种不同的卷单位！不能打印单据！");
                return;
            }
            if (string.IsNullOrEmpty ( txtkehu.Text))
            {
                Tools.ShowMessageBox.ShowErrorBox("客户名称缺失！不能打印单据");
                return;
            }
            InitDanju(); 
            var Yidabaolist = CreatJuanhao();
            try
            {
               
                switch (cmbMadanYangshi.Text)
                {
                    case "竖版样式":
                        new Tools.打印成品码单()
                        {
                            danjuTable = danju,
                            danjumingxitables = danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList(),
                            danjuinfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName = gridView1.Name },
                            juanHaoTables = CreatJuanhao(),
                            mingxiinfo = new Tools.FormInfo() { FormName = this.Name, GridviewName = gridView1.Name }
                        }.Print(PrintPath.报表模板 + "\\madan.frx", printsytle);
                        break;
                    case "清单码单":
                        new Tools.打印清单码单()
                        {
                            danjuTable = danju,
                            danjumingxitables = danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList(),
                            danjuinfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName = gridView1.Name },
                            juanHaoTables = CreatJuanhao(),
                            mingxiinfo = new Tools.FormInfo() { FormName = this.Name, GridviewName = gridView1.Name },
                            JuanInfo = new Tools.FormInfo { FormName = "打卷报表", GridviewName = gridView2.Name }
                        }.Print(PrintPath.报表模板 + "\\清单码单.frx", printsytle);
                        break;
                    case "横版样式":                      
                        if (Yidabaolist.Count > 0)
                        {
                            new Tools.打印横版码单()
                            {
                                danju = danju,
                                juanhaolist = Yidabaolist,
                                IsAccordingToLookupTables=chkOrderMabiao.Checked ,
                                formInfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName = "gridView1" },
                                danjumingxitables = danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList(),
                                mingxiinfo = new Tools.FormInfo() { FormName = this.Name, GridviewName = gridView1.Name }
                            }.打印(printsytle, PrintPath.报表模板 + "\\A4纸.frx");
                        }
                        else
                        {
                            MessageBox.Show("没有任何包装信息！打印失败", this.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                        break;
                    case "横版款号":
                        if (Yidabaolist.Count > 0)
                        {
                            new Tools.打印横版码单()
                            {
                                danju = danju,
                                juanhaolist = Yidabaolist,
                                formInfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName = "gridView1" },
                                danjumingxitables = danjumingxitables.Where(x =>!string.IsNullOrWhiteSpace( x.pingming )).ToList(),
                                mingxiinfo = new Tools.FormInfo() { FormName = this.Name, GridviewName = gridView1.Name }
                            }.打印(printsytle, PrintPath.报表模板 + "\\横版款号.frx");
                        }
                        else
                        {
                            MessageBox.Show("没有任何包装信息！打印失败", this.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        break;
                    case "包装样式":
                        if (Yidabaolist.Count > 0)
                        {
                            new Tools.打印包装码单() { danju = danju, juanhaolist = Yidabaolist, formInfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName = "gridView1" } }.打印(printsytle, PrintPath.报表模板 + "\\打包码单.frx");
                        }
                        else
                        {
                            MessageBox.Show("没有任何包装信息！打印失败", this.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        break;
                    case "手工码单":
                        new Tools.打印手工码单()
                        {
                            danju = danju,
                            juanhaolist = manualCodes,
                            formInfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName = "gridView1" },
                            danjumingxitables = danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList(),
                            mingxiinfo = new Tools.FormInfo() { FormName = this.Name, GridviewName = gridView1.Name }
                        }.Print(PrintPath.报表模板 + "\\手工码单.frx",printsytle );
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            if (string.IsNullOrWhiteSpace(danju.IsPrinter))
            {
                State = "单据已打印1次";
            }
            else
            {
                State = "单据已打印" + (danju.IsPrinter.Substring(5, danju.IsPrinter.Length - 6).TryToInt() + 1).ToString() + "次";
            }
            PrintState();
            /// 打印后询问是否保存
            AskSave();
        }
        /// <summary>
        /// 打印后询问是否保存
        /// </summary>
        private void AskSave()
        {
            if (QueryTime.PrintRule == PrintRuleStyle.PrintFirst)
            {
                if (Tools.ShowMessageBox.ShowAskBox("是否直接保存单据？") == DialogResult.Yes)
                {
                    保存ToolStripMenuItem_Click(null, null);
                }
            }
        }
        private void 码单编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (PrintService.CheckPrintDesignAccess ())
            {
                PrintMadan(PrintModel.Design);
            }
        }
        /// <summary>
        /// 标识该单据已打印
        /// </summary>
        private void PrintState()
        {
            DanjuTableService.UpdateDanjuTable($"IsPrinter='{State }'", x => x.dh == txtdanhao.Text);
        }
        private void 码单预览ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintMadan(PrintModel.Privew );          
        }

        private void 直接打印ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            PrintMadan(PrintModel.Print );         
        }
       /// <summary>
       /// 退出所有编辑状态
       /// </summary>
        private void CloseEdit()
        {
            gridView1.CloseEditor();
            gridView2.CloseEditor();
            gridView3.CloseEditor();
            gridView4.CloseEditor();
            gridView5.CloseEditor();
        }
        private void PrintDanju(PrintModel useful)
        {         
            if (useful == PrintModel.Design)
            {
                if (!PrintService.CheckPrintDesignAccess())
                {
                    return;
                }
            }
            InitDanju();
            new Tools.打印发货单()
            {
                danjuTable = danju,
                danjumingxitables = danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList(),
                danjuinfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName = gridView1.Name },
                mingxiinfo = new Tools.FormInfo() { FormName = this.Name, GridviewName = gridView1.Name }
            }.Print(cmbdanju.Text == "分米数" ? PrintPath.报表模板 + "发货单.frx" : PrintPath.报表模板 + "发货单不分米.frx", useful);
            if (string.IsNullOrWhiteSpace(danju.IsPrinter))
            {
                State = "单据已打印1次";
            }
            else
            {
                State = "单据已打印" + (danju.IsPrinter.Substring(5, danju.IsPrinter.Length - 6).TryToInt() + 1).ToString() + "次";
            }
            PrintState();
            /// 打印后询问是否保存
            AskSave();
        }
        private void 打印预览ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintDanju(PrintModel.Privew);
        }

        private void 打印编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintDanju(PrintModel.Design);
        }

        private void 直接打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintDanju(PrintModel.Print);
        }

        private void txtkehu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                var fm = new 客户选择() { linkman = new LXR() { ZJC = txtkehu.Text, MC = "" } };
                fm.ShowDialog();
                danju.ksbh = fm.linkman.BH;
                danju.ksmc = fm.linkman.MC;
                txtkehu.Text = danju.ksmc;
            }
        }

        private void 重新加载卷ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new StockHelper() { danjumingxitables = danjumingxitables, txtkehu = txtkehu }.重新加载卷(juanList, gridControl2, txtckmc.Text);
        }

        private void 保存样式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView1);
        }

        private void 保存样式ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView2);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                SettingService.Update(new Setting() { formname = this.Name, settingname = "码单样式", settingValue = cmbMadanYangshi.Text });
                MessageBox.Show("设置默认标签成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("设置默认标签失败！原因是" + ex.Message);
            }
        }

        private void dateEdit1_DateTimeChanged(object sender, EventArgs e)
        {
            //if (useful == FormUseful.新增)
            //{
            //    if (dateEdit1.DateTime == DateTime.Parse("0001-01-01 0:00:00"))
            //    {
            //        dateEdit1.DateTime = DateTime.Now;
            //    }
            //    txtdanhao.Text = BianhaoBLL.CreatDanhao(FirstLetter.销售发货单, dateEdit1.DateTime, DanjuLeiXing.销售出库单);
            //}
        }

        private void txtjiagongchang_ButtonCustomClick(object sender, EventArgs e)
        {
            var fm = new 供货商选择();
            fm.ShowDialog();
            txtjiagongchang.Text = fm.linkman.MC;
        }

        private void ckshifa_ValueChanged(object sender, bool value)
        {
            if (value)
            {
                var mishu = danjumingxitables.Sum(x => x.chengpingmishu);
                foreach(var mingxi in danjumingxitables.Where(x=>!string.IsNullOrWhiteSpace(x.pingming )).ToList ())
                {
                    mingxi.chengpingjuanshu = 1;
                    mingxi.chengpingmishu = 0;
                    mingxi.hanshuiheji = 0;
                }
                danjumingxitables[0].chengpingmishu =mishu;
                danjumingxitables[0].chengpingjuanshu = 1;
                //for (int i = 1; i < gridView1.RowCount; i++)
                //{
                //    if (!string.IsNullOrWhiteSpace(gridView1.GetRowCellValue(i, "pingming").ToString()))
                //    {
                //        gridView1.SetRowCellValue(i, "chengpingjuanshu", 1);
                //        gridView1.SetRowCellValue(i, "chengpingmishu", 0);
                //        gridView1.SetRowCellValue(i, "hanshuiheji", 0);
                //        gridView1.SetRowCellValue(i, "toupimishu", 0);
                //    }
                //}
            }
            else
            {
                foreach (var d in danjumingxitables)
                {
                    if (d.suolv != 0)
                    {
                        StockTable stock = StockTableService.GetOneStockTable(x => x.ID == d.suolv);
                        d.chengpingmishu = stock.MS;
                        d.chengpingjuanshu = stock.JS;
                        d.toupimishu = stock.MS;
                    }
                }               
            } 
            gridControl1.RefreshDataSource();
        }

        private void 相同工序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var houzhengli = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "houzhengli");
            foreach (var row in danjumingxitables)
            {
                if (!string.IsNullOrEmpty(row.pingming))
                { row.houzhengli = (string)houzhengli; }
            }
            gridControl1.RefreshDataSource();
        }

        private void 相同价格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var jiage = gridView1.GetRowCellValue(gridView1.FocusedRowHandle , "hanshuidanjia");
            foreach (var row in danjumingxitables )
            {
                if (!string.IsNullOrEmpty(row.pingming))
                {
                    row.hanshuidanjia = (decimal)jiage;
                    row.hanshuiheji = row.hanshuidanjia * row.toupimishu;
                }
            }
            gridControl1.RefreshDataSource();
        }

        private void 编辑报告ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (PrintService.CheckPrintDesignAccess())
            {
                Tools.打印检验报告.PrintReport(PrintModel.Design, CreatJuanhao());
            }
        }

        private void 预览报告ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tools.打印检验报告.PrintReport(PrintModel.Privew, CreatJuanhao());
        }

        private void 打印报告ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tools.打印检验报告.PrintReport(PrintModel.Print, CreatJuanhao());
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView3) { formname = this.Name, Obj = new AccessoriesInfo() };
            fm.ShowDialog();
        }
        /// <summary>
        /// 选择辅料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtkehu.Text))
            {
                MessageBox.Show("请先选择客户名称", "错误", MessageBoxButtons.OK);
                return;
            }
            var fm = new 库存选择() { StockName = "辅料仓库" };
            fm.ShowDialog();
            if(fm.pingzhong.Count >0)
            {
                checkBox1.Checked = true;
            }
            var i = gridView3.FocusedRowHandle;
            foreach (var pingzhong in fm.pingzhong)
            {
                AccessoriesInfos[i].bizhong = "人民币￥";
                AccessoriesInfos[i].Bianhao = pingzhong.BH;
                AccessoriesInfos[i].guige = pingzhong.GG;
                AccessoriesInfos[i].chengfeng = pingzhong.CF;
                AccessoriesInfos[i].pingming = pingzhong.PM;
                AccessoriesInfos[i].kezhong = pingzhong.KZ;
                AccessoriesInfos[i].menfu = pingzhong.MF;
                AccessoriesInfos[i].danwei = "米";
                AccessoriesInfos[i].ContractNum = pingzhong.ContractNum;
                AccessoriesInfos[i].CustomName = pingzhong.CustomName;
                AccessoriesInfos[i].OrderNum = pingzhong.orderNum;
                AccessoriesInfos[i].kuanhao = pingzhong.kuanhao;
                AccessoriesInfos[i].houzhengli = pingzhong.houzhengli;
                AccessoriesInfos[i].yanse = pingzhong.YS;
                AccessoriesInfos[i].Chengpingyanse = pingzhong.YS;
                AccessoriesInfos[i].ganghao = pingzhong.GH;
                AccessoriesInfos[i].chengpingjuanshu = pingzhong.JS;
                AccessoriesInfos[i].toupimishu = pingzhong.MS;
                AccessoriesInfos[i].chengpingmishu = pingzhong.MS;
                AccessoriesInfos[i].Kuwei = pingzhong.Kuwei;
                AccessoriesInfos[i].Huahao = pingzhong.Huahao;
                AccessoriesInfos[i].ColorNum = pingzhong.ColorNum;
                AccessoriesInfos[i].CustomerColorNum = pingzhong.CustomerColorNum;
                AccessoriesInfos[i].CustomerPingMing = pingzhong.CustomerPingMing;
                AccessoriesInfos[i].rq = dateEdit1.DateTime;
                AccessoriesInfos[i].IsHanshui = IsHanshuiModel.含税;
                AccessoriesInfos[i].suolv = pingzhong.ID;
                AccessoriesInfos[i].mashu = 100;
                AccessoriesInfos[i].rkdh = pingzhong.RKDH;
                AccessoriesInfos[i].IsDone = true;
                AccessoriesInfos[i].offerid = pingzhong.LiuzhuanCard;
                AccessoriesInfos[i].hanshuidanjia = 0;
                AccessoriesInfos[i].hanshuiheji = AccessoriesInfos[i].hanshuidanjia * pingzhong.MS;
                i++;
                if (i == AccessoriesInfos.Count - 1)
                    for (int j = 0; j < 30; j++)
                    {
                        AccessoriesInfos.Add(new AccessoriesInfo () { danhao = txtdanhao.Text, rq = Convert.ToDateTime(dateEdit1.Text) });
                    }
            }
         
            fm.Dispose();
            gridControl3.RefreshDataSource();
            gridView3.CloseEditor();
        }

        private void repositoryItemButtonEdit5_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var fm = new 原料选择();
            fm.ShowDialog();
            int rowindex = gridView4.FocusedRowHandle;
            foreach(var s in fm.SelecRaws)
            {
                Raws[rowindex]=s.Adapt<ImportAndExportOfRawMaterials>();
                Raws[rowindex].DocNum = txtdanhao.Text;
                rowindex++;
            }
            gridControl4.RefreshDataSource();
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView4) { formname = this.Name, Obj = new ImportAndExportOfRawMaterials() };
            fm.ShowDialog();
        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView4);
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView3);
        }

        private void gridView4_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                int rowindex = gridView4.FocusedRowHandle;
                Raws[rowindex].Total = Raws[rowindex].Price * Raws[rowindex].InventoryQuantity;
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowErrorBox(ex.Message);
            }
        }
        /// <summary>
        /// 手工码单修改成品信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView5_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                for (int col = 1; col < 11; col++)
                {
                    if (gridView5.FocusedColumn.FieldName == "Col" + col.ToString())
                    {
                        decimal sumcol = 0;
                        for (var c = 1; c < 11; c++)
                        {
                            sumcol += (decimal)gridView5.GetRowCellValue(gridView5.FocusedRowHandle, "Col" + c.ToString());
                        }
                        manualCodes[gridView5.FocusedRowHandle].SumCol = sumcol;
                    }
                }
                if (gridView5.FocusedColumn.FieldName == "Lot")
                {
                    var lot = gridView5.GetRowCellValue(gridView5.FocusedRowHandle, "Lot").ToString();
                    var mingxi = danjumingxitables.FirstOrDefault(x => x.ganghao == lot);
                    if (mingxi != null)
                    {
                        if (!string.IsNullOrWhiteSpace(mingxi.pingming))
                        {
                            manualCodes[gridView5.FocusedRowHandle].Color = mingxi.yanse;
                            manualCodes[gridView5.FocusedRowHandle].ItemNo = mingxi.kuanhao;
                            manualCodes[gridView5.FocusedRowHandle].FlowerPattern = mingxi.Huahao;
                        }
                    }
                }
                for (var row = 0; row < manualCodes.Count; row++)
                {
                    if (string.IsNullOrWhiteSpace(manualCodes[0].Color))
                    {
                        break;
                    }
                    else
                    {

                        if (row == 0)
                        {
                            var mingxi = danjumingxitables.FirstOrDefault(x => x.ganghao == manualCodes[row].Lot && x.yanse == manualCodes[row].Color);
                            if (mingxi != null)
                            {
                                mingxi.chengpingjuanshu = 0;
                                mingxi.chengpingmishu = 0;
                                if (!string.IsNullOrWhiteSpace(mingxi.pingming))
                                {
                                    for (var col = 1; col < 11; col++)
                                    {
                                        if ((decimal)gridView5.GetRowCellValue(row, "Col" + col.ToString()) > 0)
                                        {
                                            mingxi.chengpingjuanshu++;
                                            mingxi.chengpingmishu += (decimal)gridView5.GetRowCellValue(row, "Col" + col.ToString());
                                            mingxi.toupimishu = mingxi.chengpingmishu;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (manualCodes[row].Col1 > 0)
                            {
                                if (string.IsNullOrWhiteSpace(manualCodes[row].Lot))
                                {
                                    manualCodes[row].Color = manualCodes[row - 1].Color;
                                    manualCodes[row].ItemNo = manualCodes[row - 1].ItemNo;
                                    manualCodes[row].Lot = manualCodes[row - 1].Lot;
                                    manualCodes[row].FlowerPattern = manualCodes[row - 1].FlowerPattern;
                                }
                                else
                                {
                                    if (manualCodes[row].Lot != manualCodes[row - 1].Lot|| manualCodes[row].Color != manualCodes[row - 1].Color)
                                    {
                                        var m = danjumingxitables.FirstOrDefault(x => x.ganghao == manualCodes[row].Lot && x.yanse == manualCodes[row].Color);
                                        if (m != null)
                                        {
                                            m.chengpingjuanshu = 0;
                                            m.chengpingmishu = 0;
                                        }
                                    }
                                }
                                var mingxi = danjumingxitables.FirstOrDefault(x => x.ganghao == manualCodes[row].Lot && x.yanse == manualCodes[row].Color);
                                if (mingxi!=null)
                                {
                                    for (var col = 1; col < 11; col++)
                                    {
                                        if ((decimal)gridView5.GetRowCellValue(row, "Col" + col.ToString()) > 0)
                                        {
                                            mingxi.chengpingjuanshu++;
                                            mingxi.chengpingmishu += (decimal)gridView5.GetRowCellValue(row, "Col" + col.ToString());
                                            mingxi.toupimishu = mingxi.chengpingmishu;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                gridControl1.RefreshDataSource();
                gridControl5.RefreshDataSource();
            }
            catch(Exception ex)
            {
                ShowMessageBox.ShowErrorBox("计算的时候发生了错误：" + ex.Message);
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBox1.Checked)
            {
               checkBox1.Checked= ShowMessageBox.ShowAskBox("您确定当前是复合发货吗？复合发货将不再减少成品信息库存！只减少辅料信息库存")==DialogResult.Yes;
            }
        }

        private void 删除行ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            gridView4.DeleteSelectedRows();
        }

        private void 删除行ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            gridView3.DeleteSelectedRows();
        }

        private void 添加行ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            gridView3.AddNewRow();
        }

        private void 添加行ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            gridView4.AddNewRow();
        }

        private void 选择布料ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SelectFabric();
        }

        private void 新增ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Init();
            SaveState = !SaveState;
            useful = FormUseful.新增;
            SaveStateChange();
        }

        private void 修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveState = !SaveState;
            useful = FormUseful.修改;
            SaveStateChange();
        }

        private void StevedoringChargesFreeNuminput_ValueChanged(object sender, EventArgs e)
        {
            ComputeTotalMoney();
        }
    }
}
